package user

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/admin"
	"time"

	"github.com/gin-gonic/gin"
)

func InsertUser(c *gin.Context) {
	requestDataStruct := struct {
		Username string `json:"username"`
		Status   int    `json:"status"`
		Password string `json:"password"`
	}{}

	c.ShouldBindJSON(&requestDataStruct)

	var adminStruct admin.AdminStruct
	exists, err := model.GetModelDataFirst(
		model.Db,
		adminStruct.TableName(),
		&adminStruct,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"username":   requestDataStruct.Username,
				"created_at": time.Now(),
			},
			Debug: true,
		})

	if exists {
		controller.Fail(c, "当前用户名已存在")
		return
	}

	if err != nil {
		controller.Fail(c, fmt.Sprintf("创建用户失败%s", err.Error()))
		return
	}

	//密码盐
	salt := controller.GenerateString(4)

	//生成密码
	data := []byte(requestDataStruct.Password + "|" + salt)
	hash := md5.Sum(data)
	hashString := hex.EncodeToString(hash[:])

	adminStruct.CreateUser(admin.AdminStruct{
		Username: requestDataStruct.Username,
		Password: hashString,
		Salt:     salt,
		Status:   requestDataStruct.Status,
		GroupId:  7,
	})

	controller.Success(c, "")
}
